package com.hqyj.hrms.modules.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.hrms.modules.account.dao.RoleMapper;
import com.hqyj.hrms.modules.account.entity.Role;
import com.hqyj.hrms.modules.account.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {

    //注入mapper
    @Autowired(required = false)
    RoleMapper roleMapper;


    @Override
    public List<Role> getRoles() {
        return Optional.ofNullable(roleMapper.getRoles()).orElse(Collections.emptyList());
    }

    @Override
    public List<Role> getRolesByUserId(int userId) {
//        return roleMapper.getRolesByUserId(userId);
        return roleMapper.getRoles();
    }

    @Override
    public HashMap<String, Object> add(Role role) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        int num = roleMapper.insert(role);
        if (num > 0) {
            map.put("info", "新增成功");
        } else {
            map.put("info", "新增失败");
        }
        return map;
    }

    //修改
    @Override
    public HashMap<String, Object> update(Role role) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        int num = roleMapper.updateById(role);
        if (num > 0) {
            map.put("info", "修改成功");
        } else {
            map.put("info", "修改失败");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> del(Integer id) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        int num = roleMapper.deleteById(id);
        if (num > 0) {
            map.put("info", "删除成功");
        } else {
            map.put("info", "删除失败");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> list(Role role) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //第一步：创建分页对象
        Page<Role> roleInfoPage = new Page<>(role.getPage(), role.getRow());
        //创建查询条件对象
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(
                role.getRoleName() != null && !role.getRoleName().equals(""),
                "role_name",
                role.getRoleName());

        //第二步：查询分页，获取分页数据集
        Page<Role> pageList = roleMapper.selectPage(roleInfoPage, queryWrapper);
        //获取当前页的集合
        map.put("info", pageList.getRecords());
        //获取总条数
        map.put("total", pageList.getTotal());
        //获取总页数
        map.put("totalPage", pageList.getPages());
        return map;
    }


}
